package com.qf.myrbac.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.myrbac.annotation.DataFilter;
import com.qf.myrbac.sys.entity.SysDept;
import com.qf.myrbac.sys.entity.SysUser;
import com.qf.myrbac.sys.dao.SysUserDao;
import com.qf.myrbac.sys.service.SysDeptService;
import com.qf.myrbac.sys.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.myrbac.utils.Constants;
import com.qf.myrbac.utils.PageQueryUtil;
import com.qf.myrbac.utils.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author 徐英海
 * @since 2022-10-27
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {
    @Autowired
    private SysDeptService deptService;

    @DataFilter(dataField = "dept_id")
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PageVo<SysUser> queryUserByPage(Map<String, Object> params) {
        Page<SysUser> page = PageQueryUtil.getPage(params);
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        Object name = params.get("username");
        Object dataFileter = params.get(Constants.DATA_FILETER);
        String sql = dataFileter != null ? dataFileter.toString() : null;
        String username = name != null ? name.toString() : null;
        userQueryWrapper.eq(StringUtils.isNotBlank(username), "username", username)
                .eq("status", 1)
                .apply(StringUtils.isNotBlank(sql), sql);
        this.page(page, userQueryWrapper);
        List<SysDept> deptList = deptService.list();
        Map<Long, String> map = new HashMap<>();
        deptList.forEach(dept -> map.put(dept.getDeptId(), dept.getName()));
        page.getRecords().forEach(user -> user.setDeptName(map.get(user.getDeptId())));
        return new PageVo<>(page);
    }
}
